<template>
  <div class="user-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
          <el-button type="primary" @click="handleEditProfile" icon="Edit">编辑资料</el-button>
        </div>
      </template>

      <div class="user-info">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar" class="user-avatar" />
          <div class="profile-badge" @click="showAvatarDialog">
            <el-icon><Camera /></el-icon>
          </div>
        </div>
        <div class="user-details">
          <h3>{{ userInfo.nickname }}</h3>
          <p class="user-email">
            <el-icon><Message /></el-icon>
            {{ userInfo.email }}
          </p>
          <p class="user-id">用户ID: {{ userInfo.id }}</p>
          <p class="user-join">注册时间: {{ userInfo.joinTime }}</p>
        </div>
      </div>

      <el-divider />

      <!-- 用户统计 -->
      <div class="user-stats">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.orderCount }}</div>
              <div class="stat-label">累计订单</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">¥{{ userStats.totalExpense }}</div>
              <div class="stat-label">累计消费</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.favoriteCount }}</div>
              <div class="stat-label">收藏菜品</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 功能菜单 -->
    <el-card class="menu-card">
      <template #header>
        <div class="card-header">
          <h3>我的功能</h3>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="menu-item" @click="router.push('/order')">
            <el-icon size="28"><Document /></el-icon>
            <span>我的订单</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="menu-item" @click="router.push('/cart')">
            <el-icon size="28"><ShoppingCart /></el-icon>
            <span>购物车</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="menu-item" @click="handleEditProfile">
            <el-icon size="28"><Edit /></el-icon>
            <span>编辑资料</span>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <div class="menu-item" @click="handleAddress">
            <el-icon size="28"><Location /></el-icon>
            <span>收货地址</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="menu-item" @click="handleSecurity">
            <el-icon size="28"><Lock /></el-icon>
            <span>安全设置</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="menu-item" @click="handleLogout">
            <el-icon size="28"><SwitchButton /></el-icon>
            <span>退出登录</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 最近订单 -->
    <el-card class="recent-orders-card">
      <template #header>
        <div class="card-header">
          <h3>最近订单</h3>
          <el-button type="primary" text @click="router.push('/order')">查看全部</el-button>
        </div>
      </template>

      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="180" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="totalAmount" label="金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button type="primary" text @click="viewOrderDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="editProfileDialogVisible" title="编辑个人资料" width="500px" class="custom-dialog">
      <div class="dialog-header">
        <h3>编辑个人资料</h3>
      </div>
      <div class="form-container">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="头像">
            <div style="display: flex; align-items: center; gap: 15px;">
              <el-avatar :size="60" :src="editForm.avatar" />
              <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-button type="primary" size="small">更换头像</el-button>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="editForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="简介">
            <el-input
              v-model="editForm.bio"
              type="textarea"
              :rows="3"
              placeholder="请输入个人简介"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button @click="editProfileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="400px" class="custom-dialog">
      <div class="dialog-header">
        <h3>修改密码</h3>
      </div>
      <div class="form-container">
        <el-form :model="passwordForm" label-width="80px" :rules="passwordRules" ref="passwordFormRef">
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input v-model="passwordForm.currentPassword" type="password" placeholder="请输入当前密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" />
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button @click="changePasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePassword">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Document, 
  ShoppingCart, 
  Edit, 
  Location, 
  Lock, 
  SwitchButton,
  Message,
  Camera
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

interface UserInfo {
  id: number
  email: string
  nickname: string
  avatar: string
  joinTime: string
  bio?: string
}

interface Order {
  id: number
  orderNumber: string
  totalAmount: number
  status: string
  createTime: string
}

interface UserStats {
  orderCount: number
  totalExpense: number
  favoriteCount: number
}

const userInfo = ref<UserInfo>({
  id: 10001,
  email: 'user@example.com',
  nickname: '美食爱好者',
  avatar: 'https://pic1.zhimg.com/80/v2-6afa723dc9c4129aee06d8f0d2e7ecc1_720w.webp',
  joinTime: '2023-01-15',
  bio: '热爱美食的吃货一枚~'
})

const userStats = ref<UserStats>({
  orderCount: 12,
  totalExpense: 1258,
  favoriteCount: 8
})

const recentOrders = ref<Order[]>([
  {
    id: 1,
    orderNumber: 'ORD202409030001',
    totalAmount: 128,
    status: 'completed',
    createTime: '2025-09-07 10:30:00'
  },
  {
    id: 2,
    orderNumber: 'ORD202409020001',
    totalAmount: 88,
    status: 'paid',
    createTime: '2025-09-06 14:20:00'
  }
])

// 编辑资料表单
const editForm = reactive({
  nickname: userInfo.value.nickname,
  email: userInfo.value.email,
  avatar: userInfo.value.avatar,
  bio: userInfo.value.bio || ''
})

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 对话框显示状态
const editProfileDialogVisible = ref(false)
const changePasswordDialogVisible = ref(false)
const passwordFormRef = ref()

// 检查登录状态
const checkLogin = () => {
  const token = localStorage.getItem('token')
  const userData = localStorage.getItem('userInfo')
  
  if (!token || !userData) {
    ElMessage.warning('请先登录')
    router.push('/')
    return false
  }

  try {
    const parsedData = JSON.parse(userData)
    userInfo.value = { ...userInfo.value, ...parsedData }
    editForm.nickname = userInfo.value.nickname
    editForm.email = userInfo.value.email
    editForm.avatar = userInfo.value.avatar
    editForm.bio = userInfo.value.bio || ''
    return true
  } catch (error) {
    ElMessage.error('用户信息解析失败')
    return false
  }
}

const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'warning',
    paid: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待支付',
    paid: '已支付',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知状态'
}

const handleEditProfile = () => {
  editProfileDialogVisible.value = true
}

const handleAddress = () => {
  ElMessageBox.confirm(
    '您将要管理收货地址',
    '收货地址管理',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.info('打开地址管理页面')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const handleSecurity = () => {
  ElMessageBox.confirm(
    '您将要进行安全设置',
    '安全设置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    changePasswordDialogVisible.value = true
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    ElMessage.success('已安全退出')
    router.push('/')
  })
}

const viewOrderDetail = (order: Order) => {
  ElMessage.info(`查看订单详情：${order.orderNumber}`)
}

const saveProfile = () => {
  userInfo.value.nickname = editForm.nickname
  userInfo.value.email = editForm.email
  userInfo.value.avatar = editForm.avatar
  userInfo.value.bio = editForm.bio
  
  // 更新本地存储
  localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  
  ElMessage.success('个人资料更新成功')
  editProfileDialogVisible.value = false
}

const savePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    // 模拟密码修改成功
    ElMessage.success('密码修改成功')
    changePasswordDialogVisible.value = false
    
    // 清空表单
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    ElMessage.error('请正确填写表单')
  }
}

const beforeAvatarUpload = (file: File) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }

  return isJPGOrPNG && isLt2M
}

const handleAvatarUpload = (options: any) => {
  const { file } = options
  // 模拟上传成功
  const reader = new FileReader()
  reader.onload = (e) => {
    editForm.avatar = e.target?.result as string
    ElMessage.success('头像上传成功')
  }
  reader.readAsDataURL(file)
}

const showAvatarDialog = () => {
  ElMessage.info('打开头像编辑功能')
}

onMounted(() => {
  if (checkLogin()) {
    // 加载用户数据
  }
})
</script>

<style scoped>
:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --bg-color: #f5f7fa;
  --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  --hover-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.user-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.user-card, .menu-card, .recent-orders-card {
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: var(--card-shadow);
  transition: all 0.3s ease;
  border: none;
}

.user-card:hover, .menu-card:hover, .recent-orders-card:hover {
  box-shadow: var(--hover-shadow);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(90deg, #f9fafc 0%, #f5f7fa 100%);
  border-radius: 12px 12px 0 0;
}

.card-header h2 {
  color: #303133;
  font-weight: 600;
  font-size: 18px;
  margin: 0;
}

.card-header h3 {
  color: #303133;
  font-weight: 600;
  font-size: 16px;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 24px;
  gap: 24px;
}

.user-avatar {
  flex-shrink: 0;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-details {
  flex: 1;
}

.user-details h3 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.user-email {
  color: var(--info-color);
  margin-bottom: 6px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-id {
  color: var(--info-color);
  font-size: 14px;
  margin-bottom: 4px;
}

.user-join {
  color: var(--info-color);
  font-size: 14px;
  margin: 0;
}

.user-stats {
  padding: 0 24px 24px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #f9fafc 0%, #f5f7fa 100%);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-3px);
  background: linear-gradient(135deg, #ecf5ff 0%, #f5f7fa 100%);
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: var(--primary-color);
  margin-bottom: 8px;
}

.stat-label {
  color: var(--info-color);
  font-size: 14px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  background: #fff;
}

.menu-item:hover {
  background: #f5f7fa;
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.menu-item span {
  margin-top: 10px;
  font-size: 14px;
  font-weight: 500;
}

.el-divider {
  margin: 0;
}

.recent-orders-card .el-table {
  border-radius: 0 0 8px 8px;
  overflow: hidden;
}

.recent-orders-card .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.profile-badge {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: var(--primary-color);
  color: white;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #fff;
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }
  
  .user-stats .el-col {
    margin-bottom: 15px;
  }
  
  .menu-card .el-col {
    margin-bottom: 15px;
  }
}

/* 自定义对话框样式 */
:deep(.custom-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.custom-dialog .el-dialog__header) {
  padding: 0;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 0;
}

.dialog-header {
  background: linear-gradient(90deg, #f9fafc 0%, #f5f7fa 100%);
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-header h3 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

.form-container {
  padding: 20px;
}

.dialog-footer {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
</style>